from threading import Thread
from MsgProcess import MsgProcess, MsgType
import xml.dom.minidom
import json,requests,time



class Journalism(MsgProcess):



    def Start(self, message):
        time.sleep(10)
        #设置新闻间隔时间
        self.Interval_time=6
        self.mythread=Thread(  target=lambda : self.post( self.Text() ) )
        self.mythread.start()




    def post(self,data):
        nowtime=time.time()
        while 1:
            #每个小时获取最新新闻
            if time.time()-nowtime >=3600:
                nowtime=time.time()
                data= self.Text()
                time.sleep(1)
                
            if not data: 
                data = self.Text()
                time.sleep(1)
                    
            for y in data:
                datas = {  "type":"exejs","data":"Journalism_text('{0}','{1}')".format( data[y][1]+data[y][0],data[y][2] )   }
                self.send( MsgType=MsgType.Text, Receiver="Screen", Data= datas )
                time.sleep(self.Interval_time)



    #执行入口
    def Text(self, message=None):

        url=[

            "http://www.people.com.cn/rss/politics.xml",     #	国内新闻
            "http://www.people.com.cn/rss/world.xml",       #  国际新闻
            #"http://www.people.com.cn/rss/finance.xml",     #	经济新闻
            #"http://www.people.com.cn/rss/sports.xml",	     #	体育新闻
            #"http://www.people.com.cn/rss/haixia.xml",	     #  台湾新闻
            #"http://www.people.com.cn/rss/edu.xml",	         #	教育新闻
            #"http://www.people.com.cn/rss/bbs.xml",	         #	强国论坛
            #"http://www.people.com.cn/rss/game.xml",	     #	游戏新闻
            #"http://www.people.com.cn/rss/opml.xml",	     #	中文新闻
            #"http://www.people.com.cn/rss/opml_en.xml",      #	英文新闻
            #"http://www.people.com.cn/rss/opml_ru.xml"       #  俄文新闻

            ]
        data ={}
        number=0
        for x in url:
            try:
                r=requests.get(x,timeout=10)
                #打开xml文档
                dom = xml.dom.minidom.parseString(r.content)
                #得到文档元素对象
                root = dom.documentElement

                name_list = root.getElementsByTagName('author')
                time_list = root.getElementsByTagName('pubDate')
                data_list = root.getElementsByTagName('title')
                
                for n,t,d in zip(name_list,time_list,data_list):
                    data[number]=[str(n.firstChild.data),str(t.firstChild.data),str(d.firstChild.data)]
                    number+=1
            except:
                continue

        return  data